#include "qmlbridge.h"
#include <QQmlEngine>
#include <QDebug>
#include <QDateTime>
#include <QVariantMap>
#include <QJsonObject>
#include <QJsonDocument>

QmlBridge::QmlBridge(QObject *parent)
    : QObject(parent)
    , m_engine(nullptr)
    , m_deviceController(nullptr)
    , m_samplingManager(nullptr)
    , m_auditLogger(nullptr)
    , m_userSession(nullptr)
    , m_permissionManager(nullptr)
{
}

QmlBridge::~QmlBridge()
{
}

bool QmlBridge::initialize(QQmlApplicationEngine* engine)
{
    if (!engine) {
        qDebug() << "QmlBridge: Invalid QML engine";
        return false;
    }
    
    m_engine = engine;
    
    // Register QML types
    registerQmlTypes();
    
    // Setup context properties
    setupContextProperties();
    
    qDebug() << "QmlBridge initialized successfully";
    return true;
}

void QmlBridge::registerQmlTypes()
{
    // Register enums for QML
    qmlRegisterType<QmlEnums>("BacteriaSampler", 1, 0, "Enums");
    
    // Register this bridge as a singleton
    qmlRegisterSingletonType<QmlBridge>("BacteriaSampler", 1, 0, "QmlBridge",
        [](QQmlEngine *engine, QJSEngine *scriptEngine) -> QObject * {
            Q_UNUSED(engine)
            Q_UNUSED(scriptEngine)
            return new QmlBridge();
        });
}

void QmlBridge::setupContextProperties()
{
    if (!m_engine) return;
    
    // Make this bridge available to QML
    m_engine->rootContext()->setContextProperty("qmlBridge", this);
    
    qDebug() << "QML context properties set up";
}

// User authentication methods
bool QmlBridge::loginUser(const QString& username, const QString& password)
{
    qDebug() << "Login attempt for user:" << username;
    
    if (!m_userSession) {
        qDebug() << "User session not available";
        return false;
    }
    
    // Validate credentials (this would normally check against database)
    bool isValid = false;
    if (username == "admin" && password == "admin123") {
        isValid = true;
    } else if (username == "operator" && password == "operator123") {
        isValid = true;
    } else if (username == "viewer" && password == "viewer123") {
        isValid = true;
    }
    
    if (isValid) {
        // Set user session
        // m_userSession->setCurrentUser(username);
        
        // Log successful login
        logUserOperation("LOGIN", QString("User %1 logged in successfully").arg(username));
        
        emit userLoginStatusChanged(true);
        emit currentUserChanged(username);
        emit currentUserRoleChanged(getCurrentUserRole());
        
        updateUserPermissions();
        
        qDebug() << "User login successful:" << username;
        return true;
    }
    
    // Log failed login attempt
    logUserOperation("LOGIN_FAILED", QString("Failed login attempt for user %1").arg(username));
    
    qDebug() << "User login failed:" << username;
    return false;
}

void QmlBridge::logoutUser()
{
    QString currentUser = getCurrentUser();
    
    if (!currentUser.isEmpty()) {
        logUserOperation("LOGOUT", QString("User %1 logged out").arg(currentUser));
    }
    
    // Clear user session
    if (m_userSession) {
        // m_userSession->clearSession();
    }
    
    emit userLoginStatusChanged(false);
    emit currentUserChanged("");
    emit currentUserRoleChanged("");
    emit permissionsChanged();
    
    qDebug() << "User logged out:" << currentUser;
}

bool QmlBridge::logUserLogin(const QString& username, bool success)
{
    if (!m_auditLogger) {
        qDebug() << "AuditLogger not available for login logging";
        return false;
    }
    
    AuditLogger::AuditRecord record;
    record.timestamp = QDateTime::currentDateTime();
    record.userId = username;
    record.action = success ? AuditLogger::Login : AuditLogger::System;
    record.tableName = "users";
    record.recordId = username;
    record.oldValue = "";
    record.newValue = success ? "Login successful" : "Login failed";
    record.description = success ? 
        QString("User %1 logged in successfully").arg(username) :
        QString("Failed login attempt for user %1").arg(username);
    
    bool result = m_auditLogger->logEvent(record);
    qDebug() << "Login audit logged for user:" << username << "Success:" << success << "Result:" << result;
    return result;
}

bool QmlBridge::logUserLogout(const QString& username)
{
    if (!m_auditLogger) {
        qDebug() << "AuditLogger not available for logout logging";
        return false;
    }
    
    AuditLogger::AuditRecord record;
    record.timestamp = QDateTime::currentDateTime();
    record.userId = username;
    record.action = AuditLogger::Logout;
    record.tableName = "users";
    record.recordId = username;
    record.oldValue = "Logged in";
    record.newValue = "Logged out";
    record.description = QString("User %1 logged out").arg(username);
    
    bool result = m_auditLogger->logEvent(record);
    qDebug() << "Logout audit logged for user:" << username << "Result:" << result;
    return result;
}

bool QmlBridge::isUserLoggedIn() const
{
    // For demo purposes, we'll simulate a logged-in state
    // In a real implementation, check m_userSession
    return true; // Temporary for testing
}

QString QmlBridge::getCurrentUser() const
{
    // For demo purposes, return a default user
    // In a real implementation, get from m_userSession
    return "admin"; // Temporary for testing
}

QString QmlBridge::getCurrentUserRole() const
{
    QString user = getCurrentUser();
    if (user == "admin") return "管理员";
    if (user == "operator") return "操作员";
    if (user == "viewer") return "查看者";
    return "未知";
}

// Permission checking methods
bool QmlBridge::hasDeviceControl() const
{
    QString user = getCurrentUser();
    return user == "admin" || user == "operator";
}

bool QmlBridge::hasUserManagement() const
{
    QString user = getCurrentUser();
    return user == "admin";
}

bool QmlBridge::hasDataExport() const
{
    QString user = getCurrentUser();
    return user == "admin" || user == "operator";
}

bool QmlBridge::hasPermission(const QString& permission) const
{
    if (!m_permissionManager) {
        // Default permissions for demo
        QString user = getCurrentUser();
        if (user == "admin") return true;
        if (user == "operator" && (permission == "device_control" || permission == "data_export")) return true;
        if (user == "viewer" && permission == "view_data") return true;
        return false;
    }
    
    // Use permission manager
    // return m_permissionManager->hasPermission(getCurrentUser(), permission);
    return true; // Temporary for testing
}

// Device control interface methods
bool QmlBridge::startDevice()
{
    if (!hasDeviceControl()) {
        emit systemError("权限不足：无法启动设备");
        return false;
    }
    
    if (!m_deviceController) {
        emit systemError("设备控制器不可用");
        return false;
    }
    
    bool success = m_deviceController->initializeDevice();
    
    if (success) {
        logUserOperation("START_DEVICE", "设备启动成功");
        emit notificationRequested("设备状态", "设备启动成功", static_cast<int>(QmlEnums::SuccessNotification));
    } else {
        QString error = m_deviceController->getLastError();
        logUserOperation("START_DEVICE_FAILED", QString("设备启动失败: %1").arg(error));
        emit systemError(QString("设备启动失败: %1").arg(error));
    }
    
    return success;
}

bool QmlBridge::stopDevice()
{
    if (!hasDeviceControl()) {
        emit systemError("权限不足：无法停止设备");
        return false;
    }
    
    if (!m_deviceController) {
        emit systemError("设备控制器不可用");
        return false;
    }
    
    m_deviceController->shutdownDevice();
    
    logUserOperation("STOP_DEVICE", "设备停止");
    emit notificationRequested("设备状态", "设备已停止", static_cast<int>(QmlEnums::InfoNotification));
    
    return true;
}

bool QmlBridge::startSampling(int mode, int parameter)
{
    if (!hasDeviceControl()) {
        emit systemError("权限不足：无法启动采样");
        return false;
    }
    
    if (!m_deviceController) {
        emit systemError("设备控制器不可用");
        return false;
    }
    
    SamplingMode samplingMode = intToSamplingMode(mode);
    bool success = m_deviceController->startSampling(samplingMode, parameter);
    
    if (success) {
        QString modeStr = samplingModeToString(samplingMode);
        logUserOperation("START_SAMPLING", QString("开始采样 - 模式: %1, 参数: %2").arg(modeStr).arg(parameter));
        emit notificationRequested("采样状态", "采样已开始", static_cast<int>(QmlEnums::SuccessNotification));
    } else {
        QString error = m_deviceController->getLastError();
        logUserOperation("START_SAMPLING_FAILED", QString("采样启动失败: %1").arg(error));
        emit systemError(QString("采样启动失败: %1").arg(error));
    }
    
    return success;
}

bool QmlBridge::stopSampling()
{
    if (!hasDeviceControl()) {
        emit systemError("权限不足：无法停止采样");
        return false;
    }
    
    if (!m_deviceController) {
        emit systemError("设备控制器不可用");
        return false;
    }
    
    bool success = m_deviceController->stopSampling();
    
    if (success) {
        logUserOperation("STOP_SAMPLING", "采样停止");
        emit notificationRequested("采样状态", "采样已停止", static_cast<int>(QmlEnums::InfoNotification));
    } else {
        QString error = m_deviceController->getLastError();
        emit systemError(QString("采样停止失败: %1").arg(error));
    }
    
    return success;
}

QVariant QmlBridge::getDeviceStatus() const
{
    if (!m_deviceController) {
        QVariantMap status;
        status["status"] = "DEVICE_ERROR";
        status["statusText"] = "设备控制器不可用";
        return status;
    }
    
    QVariantMap status;
    status["status"] = deviceStatusToString(m_deviceController->getDeviceStatus());
    status["statusText"] = m_deviceController->getDeviceStatusString();
    status["lastError"] = m_deviceController->getLastError();
    
    return status;
}

QVariant QmlBridge::getDeviceParameters() const
{
    if (!m_deviceController) {
        return QVariantMap();
    }
    
    QVariantMap params;
    params["flowRate"] = m_deviceController->getFlowRate();
    params["batteryLevel"] = m_deviceController->getBatteryLevel();
    params["fanSpeed"] = m_deviceController->getFanSpeed();
    params["temperature"] = m_deviceController->getTemperature();
    params["humidity"] = m_deviceController->getHumidity();
    
    return params;
}

// Sampling management interface methods
int QmlBridge::createSamplingTask(const QString& taskName, int mode, int parameter, 
                                 const QString& scheduledTime, bool isRecurring)
{
    if (!hasDeviceControl()) {
        emit systemError("权限不足：无法创建采样任务");
        return -1;
    }
    
    if (!m_samplingManager) {
        emit systemError("采样管理器不可用");
        return -1;
    }
    
    QDateTime scheduleDateTime = stringToDateTime(scheduledTime);
    if (!scheduleDateTime.isValid()) {
        emit systemError("无效的计划时间格式");
        return -1;
    }
    
    int taskId = -1;
    if (mode == static_cast<int>(QmlEnums::TimedSampling)) {
        taskId = m_samplingManager->createTimedSamplingTask(taskName, parameter, scheduleDateTime, isRecurring);
    } else if (mode == static_cast<int>(QmlEnums::VolumeSampling)) {
        taskId = m_samplingManager->createVolumeSamplingTask(taskName, parameter, scheduleDateTime, isRecurring);
    }
    
    if (taskId > 0) {
        logUserOperation("CREATE_TASK", QString("创建采样任务: %1 (ID: %2)").arg(taskName).arg(taskId));
        emit notificationRequested("任务管理", QString("任务 '%1' 创建成功").arg(taskName), 
                                 static_cast<int>(QmlEnums::SuccessNotification));
    } else {
        emit systemError("采样任务创建失败");
    }
    
    return taskId;
}

bool QmlBridge::deleteSamplingTask(int taskId)
{
    if (!hasDeviceControl()) {
        emit systemError("权限不足：无法删除采样任务");
        return false;
    }
    
    if (!m_samplingManager) {
        emit systemError("采样管理器不可用");
        return false;
    }
    
    bool success = m_samplingManager->deleteTask(taskId);
    
    if (success) {
        logUserOperation("DELETE_TASK", QString("删除采样任务 ID: %1").arg(taskId));
        emit notificationRequested("任务管理", "任务删除成功", static_cast<int>(QmlEnums::InfoNotification));
    } else {
        emit systemError("任务删除失败");
    }
    
    return success;
}

QVariantList QmlBridge::getSamplingTasks() const
{
    if (!m_samplingManager) {
        return QVariantList();
    }
    
    return m_samplingManager->getAllTasks();
}

QVariantList QmlBridge::getSamplingHistory() const
{
    if (!m_deviceController) {
        return QVariantList();
    }
    
    return m_deviceController->getSamplingHistory();
}

// User management interface methods
bool QmlBridge::createUser(const QString& username, const QString& password, 
                          const QString& role, const QString& fullName)
{
    if (!hasUserManagement()) {
        emit systemError("权限不足：无法创建用户");
        return false;
    }
    
    // This would normally use a user management system
    logUserOperation("CREATE_USER", QString("创建用户: %1 (%2)").arg(username).arg(role));
    emit notificationRequested("用户管理", QString("用户 '%1' 创建成功").arg(username), 
                             static_cast<int>(QmlEnums::SuccessNotification));
    
    return true;
}

bool QmlBridge::deleteUser(const QString& username)
{
    if (!hasUserManagement()) {
        emit systemError("权限不足：无法删除用户");
        return false;
    }
    
    if (username == getCurrentUser()) {
        emit systemError("不能删除当前登录用户");
        return false;
    }
    
    // This would normally use a user management system
    logUserOperation("DELETE_USER", QString("删除用户: %1").arg(username));
    emit notificationRequested("用户管理", QString("用户 '%1' 删除成功").arg(username), 
                             static_cast<int>(QmlEnums::InfoNotification));
    
    return true;
}

bool QmlBridge::changeUserPassword(const QString& username, const QString& newPassword)
{
    if (!hasUserManagement() && username != getCurrentUser()) {
        emit systemError("权限不足：无法修改用户密码");
        return false;
    }
    
    // This would normally use a user management system
    logUserOperation("CHANGE_PASSWORD", QString("修改用户密码: %1").arg(username));
    emit notificationRequested("用户管理", "密码修改成功", static_cast<int>(QmlEnums::SuccessNotification));
    
    return true;
}

QVariantList QmlBridge::getAllUsers() const
{
    if (!hasUserManagement()) {
        return QVariantList();
    }
    
    // Return demo users
    QVariantList users;
    
    QVariantMap admin;
    admin["username"] = "admin";
    admin["fullName"] = "系统管理员";
    admin["role"] = "管理员";
    admin["lastLogin"] = QDateTime::currentDateTime().addSecs(-2 * 3600);
    users.append(admin);
    
    QVariantMap operator_;
    operator_["username"] = "operator";
    operator_["fullName"] = "设备操作员";
    operator_["role"] = "操作员";
    operator_["lastLogin"] = QDateTime::currentDateTime().addSecs(-1 * 3600);
    users.append(operator_);
    
    QVariantMap viewer;
    viewer["username"] = "viewer";
    viewer["fullName"] = "数据查看员";
    viewer["role"] = "查看者";
    viewer["lastLogin"] = QDateTime::currentDateTime().addDays(-1);
    users.append(viewer);
    
    return users;
}

// Audit log interface methods
QVariantList QmlBridge::getAuditLogs(const QString& fromDate, const QString& toDate, 
                                    const QString& userId, const QString& action) const
{
    if (!m_auditLogger) {
        qDebug() << "AuditLogger not available for getAuditLogs";
        return QVariantList();
    }
    
    // Convert parameters and query audit logs
    QDateTime from = fromDate.isEmpty() ? QDateTime() : stringToDateTime(fromDate);
    QDateTime to = toDate.isEmpty() ? QDateTime() : stringToDateTime(toDate);
    
    // Get real audit logs from the audit logger
    QList<AuditLogger::AuditRecord> records = m_auditLogger->getAuditRecords(from, to, userId, action);
    
    QVariantList logs;
    for (const auto& record : records) {
        QVariantMap log;
        log["timestamp"] = record.timestamp.toString("yyyy-MM-dd hh:mm:ss");
        log["userId"] = record.userId;
        log["action"] = static_cast<int>(record.action);
        log["tableName"] = record.tableName;
        log["recordId"] = record.recordId;
        log["oldValue"] = record.oldValue;
        log["newValue"] = record.newValue;
        log["description"] = record.description;
        logs.append(log);
    }
    
    qDebug() << "Retrieved" << logs.size() << "audit records from database";
    return logs;
}

bool QmlBridge::exportAuditLogs(const QString& filePath, const QString& format) const
{
    if (!hasDataExport()) {
        emit const_cast<QmlBridge*>(this)->systemError("权限不足：无法导出审计日志");
        return false;
    }
    
    // This would normally use the data exporter
    // logUserOperation("EXPORT_AUDIT_LOGS", QString("导出审计日志到: %1 (格式: %2)").arg(filePath).arg(format));
    
    return true;
}

// Data visualization interface methods
QVariantList QmlBridge::getFlowRateHistory(int hours) const
{
    QVariantList history;
    QDateTime now = QDateTime::currentDateTime();
    
    // Generate sample flow rate data
    for (int i = hours; i >= 0; --i) {
        QVariantMap point;
        point["timestamp"] = now.addSecs(-i * 3600);
        point["value"] = 28 + (qrand() % 5) - 2; // 26-30 L/min
        history.append(point);
    }
    
    return history;
}

QVariantList QmlBridge::getBatteryHistory(int hours) const
{
    QVariantList history;
    QDateTime now = QDateTime::currentDateTime();
    
    // Generate sample battery data
    for (int i = hours; i >= 0; --i) {
        QVariantMap point;
        point["timestamp"] = now.addSecs(-i * 3600);
        point["value"] = 100 - (i * 2); // Gradual discharge
        history.append(point);
    }
    
    return history;
}

QVariantList QmlBridge::getSamplingStatistics(int days) const
{
    QVariantList stats;
    QDateTime now = QDateTime::currentDateTime();
    
    // Generate sample statistics
    for (int i = days; i >= 0; --i) {
        QVariantMap stat;
        stat["date"] = now.addDays(-i).date();
        stat["totalSamples"] = 5 + (qrand() % 10);
        stat["successfulSamples"] = stat["totalSamples"].toInt() - (qrand() % 2);
        stat["totalVolume"] = stat["totalSamples"].toInt() * 100;
        stat["avgFlowRate"] = 28.5;
        stats.append(stat);
    }
    
    return stats;
}

QVariant QmlBridge::getDashboardData() const
{
    QVariantMap dashboard;
    
    // Device status
    dashboard["deviceStatus"] = getDeviceStatus();
    dashboard["deviceParameters"] = getDeviceParameters();
    
    // Task statistics
    if (m_samplingManager) {
        dashboard["pendingTasks"] = m_samplingManager->getPendingTasksCount();
        dashboard["completedTasks"] = m_samplingManager->getCompletedTasksCount();
        dashboard["scheduleStatus"] = m_samplingManager->getScheduleStatusString();
    } else {
        dashboard["pendingTasks"] = 0;
        dashboard["completedTasks"] = 0;
        dashboard["scheduleStatus"] = "SCHEDULE_IDLE";
    }
    
    // Recent activity
    dashboard["recentLogs"] = getAuditLogs("", "", "", "").mid(0, 5);
    
    return dashboard;
}

// System settings interface methods
bool QmlBridge::saveSystemSettings(const QVariantMap& settings)
{
    if (!hasUserManagement()) {
        emit systemError("权限不足：无法保存系统设置");
        return false;
    }
    
    // This would normally save to configuration file or database
    logUserOperation("SAVE_SETTINGS", "保存系统设置");
    emit notificationRequested("系统设置", "设置保存成功", static_cast<int>(QmlEnums::SuccessNotification));
    
    return true;
}

QVariantMap QmlBridge::getSystemSettings() const
{
    QVariantMap settings;
    
    // Default system settings
    settings["autoStartDevice"] = true;
    settings["samplingInterval"] = 60;
    settings["batteryWarningLevel"] = 20;
    settings["dataRetentionDays"] = 30;
    settings["enableAuditLog"] = true;
    settings["language"] = "zh_CN";
    
    return settings;
}

bool QmlBridge::performSystemBackup(const QString& backupPath)
{
    if (!hasUserManagement()) {
        emit systemError("权限不足：无法执行系统备份");
        return false;
    }
    
    // This would normally perform actual backup
    logUserOperation("SYSTEM_BACKUP", QString("系统备份到: %1").arg(backupPath));
    emit notificationRequested("系统备份", "备份完成", static_cast<int>(QmlEnums::SuccessNotification));
    
    return true;
}

bool QmlBridge::restoreSystemBackup(const QString& backupPath)
{
    if (!hasUserManagement()) {
        emit systemError("权限不足：无法恢复系统备份");
        return false;
    }
    
    // This would normally perform actual restore
    logUserOperation("SYSTEM_RESTORE", QString("从备份恢复: %1").arg(backupPath));
    emit notificationRequested("系统恢复", "恢复完成", static_cast<int>(QmlEnums::SuccessNotification));
    
    return true;
}

// Message notification interface methods
void QmlBridge::showNotification(const QString& title, const QString& message, int type)
{
    emit notificationRequested(title, message, type);
}

void QmlBridge::showConfirmDialog(const QString& title, const QString& message, 
                                 const QString& callback)
{
    emit confirmDialogRequested(title, message, callback);
}

// Component setters
void QmlBridge::setDeviceController(DeviceController* controller)
{
    if (m_deviceController) {
        disconnect(m_deviceController, nullptr, this, nullptr);
    }
    
    m_deviceController = controller;
    
    if (m_deviceController) {
        connect(m_deviceController, &DeviceController::deviceStatusChanged,
                this, &QmlBridge::onDeviceStatusChanged);
        connect(m_deviceController, &DeviceController::samplingCompleted,
                this, &QmlBridge::onSamplingCompleted);
        connect(m_deviceController, &DeviceController::deviceError,
                this, &QmlBridge::onDeviceError);
    }
}

void QmlBridge::setSamplingManager(SamplingManager* manager)
{
    m_samplingManager = manager;
}

void QmlBridge::setAuditLogger(AuditLogger* logger)
{
    m_auditLogger = logger;
}

void QmlBridge::setUserSession(UserSession* session)
{
    if (m_userSession) {
        disconnect(m_userSession, nullptr, this, nullptr);
    }
    
    m_userSession = session;
    
    if (m_userSession) {
        // Connect user session signals
        // connect(m_userSession, &UserSession::userLoggedIn, this, &QmlBridge::onUserLogin);
        // connect(m_userSession, &UserSession::userLoggedOut, this, &QmlBridge::onUserLogout);
    }
}

void QmlBridge::setPermissionManager(PermissionManager* manager)
{
    m_permissionManager = manager;
}

// Private slots
void QmlBridge::onUserLogin(const QString& userId)
{
    emit userLoginStatusChanged(true);
    emit currentUserChanged(userId);
    emit currentUserRoleChanged(getCurrentUserRole());
    updateUserPermissions();
}

void QmlBridge::onUserLogout()
{
    emit userLoginStatusChanged(false);
    emit currentUserChanged("");
    emit currentUserRoleChanged("");
    emit permissionsChanged();
}

void QmlBridge::onDeviceStatusChanged(DeviceStatus status)
{
    emit deviceStatusChanged(getDeviceStatus());
}

void QmlBridge::onSamplingCompleted(const SamplingRecord& record)
{
    QVariantMap recordMap = samplingRecordToVariant(record);
    emit notificationRequested("采样完成", 
                             QString("采样完成 - 体积: %1L, 时间: %2s")
                             .arg(record.actual_volume).arg(record.actual_time),
                             static_cast<int>(QmlEnums::SuccessNotification));
}

void QmlBridge::onDeviceError(const QString& error)
{
    emit systemError(QString("设备错误: %1").arg(error));
}

// Private methods
void QmlBridge::logUserOperation(const QString& operation, const QString& details)
{
    if (m_auditLogger) {
        AuditLogger::AuditRecord record;
        record.timestamp = QDateTime::currentDateTime();
        record.userId = getCurrentUser();
        record.action = AuditLogger::System;
        record.tableName = "user_operations";
        record.recordId = QString::number(QDateTime::currentMSecsSinceEpoch());
        record.oldValue = "";
        record.newValue = details;
        record.description = QString("User Operation: %1 - %2").arg(operation).arg(details);
        
        m_auditLogger->logEvent(record);
    }
    
    qDebug() << "User Operation:" << operation << "-" << details;
}

QVariantMap QmlBridge::deviceParametersToVariant(const DeviceParameters& params) const
{
    QVariantMap map;
    map["flowRate"] = params.flow_rate;
    map["samplingTime"] = params.sampling_time;
    map["samplingVolume"] = params.sampling_volume;
    map["batteryLevel"] = params.battery_level;
    map["fanSpeed"] = params.fan_speed;
    map["temperature"] = params.temperature;
    map["humidity"] = params.humidity;
    return map;
}

QVariantMap QmlBridge::samplingRecordToVariant(const SamplingRecord& record) const
{
    QVariantMap map;
    map["startTime"] = record.start_time;
    map["endTime"] = record.end_time;
    map["actualTime"] = record.actual_time;
    map["actualVolume"] = record.actual_volume;
    map["mode"] = static_cast<int>(record.mode);
    map["status"] = static_cast<int>(record.status);
    map["operatorId"] = record.operator_id;
    return map;
}

QVariantMap QmlBridge::samplingTaskToVariant(const SamplingTask& task) const
{
    QVariantMap map;
    map["taskId"] = task.task_id;
    map["taskName"] = task.task_name;
    map["mode"] = static_cast<int>(task.mode);
    map["parameter"] = task.parameter;
    map["scheduledTime"] = task.scheduled_time;
    map["operatorId"] = task.operator_id;
    map["isRecurring"] = task.is_recurring;
    map["recurrenceInterval"] = task.recurrence_interval;
    map["isActive"] = task.is_active;
    return map;
}

bool QmlBridge::validateUserInput(const QString& input, const QString& type) const
{
    if (input.isEmpty()) return false;
    
    if (type == "username") {
        return input.length() >= 3 && input.length() <= 20;
    } else if (type == "password") {
        return input.length() >= 6;
    } else if (type == "taskname") {
        return input.length() >= 1 && input.length() <= 50;
    }
    
    return true;
}

void QmlBridge::updateUserPermissions()
{
    emit permissionsChanged();
}

// Helper methods
SamplingMode QmlBridge::intToSamplingMode(int mode) const
{
    return static_cast<SamplingMode>(mode);
}

QString QmlBridge::samplingModeToString(SamplingMode mode) const
{
    switch (mode) {
        case SAMPLING_TIMED: return "定时采样";
        case SAMPLING_VOLUME: return "定量采样";
        default: return "未知模式";
    }
}

QString QmlBridge::deviceStatusToString(DeviceStatus status) const
{
    switch (status) {
        case DEVICE_IDLE: return "空闲";
        case DEVICE_SAMPLING: return "采样中";
        case DEVICE_STOPPING: return "停止中";
        case DEVICE_ERROR: return "错误";
        case DEVICE_MAINTENANCE: return "维护中";
        default: return "未知";
    }
}

QDateTime QmlBridge::stringToDateTime(const QString& dateTimeStr) const
{
    // Try different formats
    QDateTime dt = QDateTime::fromString(dateTimeStr, Qt::ISODate);
    if (!dt.isValid()) {
        dt = QDateTime::fromString(dateTimeStr, "yyyy-MM-dd hh:mm:ss");
    }
    if (!dt.isValid()) {
        dt = QDateTime::fromString(dateTimeStr, "yyyy-MM-dd hh:mm");
    }
    return dt;
}

QString QmlBridge::dateTimeToString(const QDateTime& dateTime) const
{
    return dateTime.toString(Qt::ISODate);
}
